package com.ty.rule;

import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.cloud.nacos.NacosServiceManager;
import com.alibaba.cloud.nacos.ribbon.NacosRule;
import com.alibaba.cloud.nacos.ribbon.NacosServer;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.DynamicServerListLoadBalancer;
import com.netflix.loadbalancer.Server;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Comparator;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;


@Component
public class MyRule extends AbstractLoadBalancerRule {

    @Autowired
    private NacosDiscoveryProperties nacosDiscoveryProperties;

    @Autowired
    private NacosServiceManager nacosServiceManager;

    private static AtomicLong count = new AtomicLong(0);

    @Override
    @SneakyThrows
    public Server choose(Object key) {
        String clusterName = this.nacosDiscoveryProperties.getClusterName();
        String group = this.nacosDiscoveryProperties.getGroup();
        DynamicServerListLoadBalancer loadBalancer = (DynamicServerListLoadBalancer) getLoadBalancer();
        String name = loadBalancer.getName();
        NamingService namingService = nacosServiceManager.getNamingService();
        List<Instance> instances = namingService.selectInstances(name, group, true);
        Instance minInstance = instances.stream().min(Comparator.comparing(Instance::getWeight)).get();
        Instance maxInstance = instances.stream().max(Comparator.comparing(Instance::getWeight)).get();
        Instance selectInstance = null;
        long i = count.incrementAndGet();
        long mod =  i % 5;
        if(mod==0){
            selectInstance = minInstance;
        } else{
            selectInstance = maxInstance;
        }

        return new NacosServer(selectInstance);
    }

    @Override
    public void initWithNiwsConfig(IClientConfig clientConfig) {

        }
}
